from django.db import models
from users.models import User


class TestSuite(models.Model):
    """API测试套件"""
    name = models.CharField(max_length=200, verbose_name="套件名称")
    description = models.TextField(blank=True, verbose_name="描述")
    base_url = models.URLField(verbose_name="基础URL")
    # 修复冲突：添加 related_name
    created_by = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="创建人",
                                   related_name='api_testsuites')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        verbose_name = "API测试套件"
        verbose_name_plural = verbose_name
        ordering = ['-created_at']

    def __str__(self):
        return self.name


class TestCase(models.Model):
    """API测试用例"""
    METHOD_CHOICES = [
        ('GET', 'GET'),
        ('POST', 'POST'),
        ('PUT', 'PUT'),
        ('DELETE', 'DELETE'),
        ('PATCH', 'PATCH')
    ]

    PRIORITY_CHOICES = [
        (1, '低'),
        (2, '中'),
        (3, '高')
    ]

    suite = models.ForeignKey(TestSuite, on_delete=models.CASCADE, verbose_name="所属套件")
    name = models.CharField(max_length=200, verbose_name="用例名称")
    description = models.TextField(blank=True, verbose_name="用例描述")
    api_path = models.CharField(max_length=500, verbose_name="API路径")
    method = models.CharField(max_length=10, choices=METHOD_CHOICES, verbose_name="请求方法")
    # 修复：将 JSONField 改为 TextField
    headers = models.TextField(default='{}', verbose_name="请求头")
    parameters = models.TextField(default='{}', verbose_name="请求参数")
    expected_result = models.TextField(default='{}', verbose_name="预期结果")
    priority = models.IntegerField(choices=PRIORITY_CHOICES, default=2, verbose_name="优先级")
    order = models.IntegerField(default=0, verbose_name="执行顺序")
    is_active = models.BooleanField(default=True, verbose_name="是否启用")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")

    class Meta:
        verbose_name = "API测试用例"
        verbose_name_plural = verbose_name
        ordering = ['suite', 'order', 'id']

    def __str__(self):
        return f"{self.suite.name} - {self.name}"

    def get_headers(self):
        """获取请求头字典"""
        import json
        try:
            return json.loads(self.headers) if self.headers else {}
        except json.JSONDecodeError:
            return {}

    def get_parameters(self):
        """获取请求参数字典"""
        import json
        try:
            return json.loads(self.parameters) if self.parameters else {}
        except json.JSONDecodeError:
            return {}

    def get_expected_result(self):
        """获取预期结果字典"""
        import json
        try:
            return json.loads(self.expected_result) if self.expected_result else {}
        except json.JSONDecodeError:
            return {}


class TestExecution(models.Model):
    """API测试执行记录"""
    STATUS_CHOICES = [
        ('pending', '等待中'),
        ('running', '执行中'),
        ('success', '成功'),
        ('failed', '失败'),
        ('error', '错误')
    ]

    suite = models.ForeignKey(TestSuite, on_delete=models.CASCADE, verbose_name="测试套件")
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='pending', verbose_name="执行状态")
    started_at = models.DateTimeField(auto_now_add=True, verbose_name="开始时间")
    finished_at = models.DateTimeField(null=True, blank=True, verbose_name="结束时间")
    total_cases = models.IntegerField(default=0, verbose_name="总用例数")
    passed_cases = models.IntegerField(default=0, verbose_name="通过用例数")
    failed_cases = models.IntegerField(default=0, verbose_name="失败用例数")
    execution_log = models.TextField(blank=True, verbose_name="执行日志")
    # 修复冲突：添加 related_name
    executed_by = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="执行人",
                                    related_name='api_testexecutions')

    class Meta:
        verbose_name = "API测试执行"
        verbose_name_plural = verbose_name
        ordering = ['-started_at']

    def __str__(self):
        return f"{self.suite.name} - {self.started_at.strftime('%Y-%m-%d %H:%M')}"